-- 土豆雷类
local Plant = require("app.mode.Plant")
local AniHelper = require("app.utils.AnimateHelper")
local sfc = cc.SpriteFrameCache:getInstance()

local PotatoMine = {}
setmetatable(PotatoMine, Plant)
PotatoMine.__index = PotatoMine

PotatoMine.UNREADY = 0
PotatoMine.READY = 1

function PotatoMine:initView()
    if self:getState() == PotatoMine.UNREADY then
        self._sprite = cc.Sprite:createWithSpriteFrame(sfc:getSpriteFrameByName(self:getName() .. "_unready.png"))
        self._animate = nil
    else
        self._sprite, self._animate = AniHelper("plants/", self:getName())
    end
end

-- 重写功能函数
function PotatoMine:doFunc()
    if self._scene and self:getState() == PotatoMine.UNREADY then
        local sp
        sp, self._animate = AniHelper("plants/", self:getName())
        self._sprite:setTexture(sp:getTexture())
        self:runAnimate()

        self:setState(PotatoMine.READY)
    end
    -- 功能函数只触发一次
    self:stopLoop()
end

-- 被攻击
function PotatoMine:beAttack(attack)
    if self._scene and self:getState() == PotatoMine.UNREADY then
        Plant.beAttack(self, attack)
    else
        self:explose()
    end
end

-- 爆炸
function PotatoMine:explose()
    -- 先引爆僵尸，再移除植物
    local target = self:getTarget()
    for i = #target, 1, -1 do
        target[i]:explode()
    end

    local animation = cc.Animation:create()
    animation:setDelayPerUnit(0.1)
    animation:setLoops(1)
    animation:addSpriteFrame(self:getSprite():getSpriteFrame())
    animation:addSpriteFrame(sfc:getSpriteFrameByName(self:getName() .. "_mash.png"))
    animation:addSpriteFrame(sfc:getSpriteFrameByName(self:getName() .. "_explose.png"))
    local animate = cc.Animate:create(animation)

    self:stopAnimate()
    self._sprite:runAction(
        cc.Sequence:create(
            animate,
            cc.CallFunc:create(
                function(node, data)
                    self:removeSelf()
                end
            ),
            nil
        )
    )

    self:preRemove()

    cc.SimpleAudioEngine:getInstance():playEffect("sounds/photato_mine.ogg")
end

function PotatoMine:getState()
    return self._data.state
end

function PotatoMine:setState(val)
    self._data.state = val
end

function PotatoMine:isReady()
    return self._data.state == PotatoMine.READY
end

return PotatoMine
